package com.zsk.shop.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsk.shop.common.base.BaseResponse;
import com.zsk.shop.common.base.BizException;
import com.zsk.shop.common.base.NoMsgException;
import com.zsk.shop.common.utils.EntityConvertUtils;
import com.zsk.shop.common.utils.RedisUtil;
import com.zsk.shop.common.utils.ToolUtil;
import com.zsk.shop.entity.ShopGoods;
import com.zsk.shop.entity.ShopGoodsCategory;
import com.zsk.shop.enums.ServiceKeyTypeEnum;
import com.zsk.shop.mapper.ShopGoodsCategoryMapper;
import com.zsk.shop.model.params.GoodsCategoryParams;
import com.zsk.shop.model.params.ShopGoodsCategoryAddParams;
import com.zsk.shop.model.params.ShopGoodsCategoryEditParams;
import com.zsk.shop.model.results.ShopGoodsCategoryTreeResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ljh
 * @create 2021/11/17 16:12
 */
@Service
public class ShopGoodsCategoryService extends ServiceImpl<ShopGoodsCategoryMapper, ShopGoodsCategory> {

    @Resource
    private ShopGoodsService shopGoodsService;

    public BaseResponse<List<ShopGoodsCategory>> queryGoodsCategory(Integer level, String partnerCategoryNo, Boolean isGop) {
        LambdaQueryWrapper<ShopGoodsCategory> queryWrapper = new LambdaQueryWrapper<>();
        if (!isGop) {
            queryWrapper.eq(ShopGoodsCategory::getIsShow, true);
        }
        queryWrapper.eq(ShopGoodsCategory::getIsDeleted, false);
        if (ToolUtil.isNotEmpty(level)) {
            queryWrapper.eq(ShopGoodsCategory::getLevel, level);
            if (ToolUtil.isNotEmpty(partnerCategoryNo)) {
                queryWrapper.eq(ShopGoodsCategory::getPartnerCategoryNo, partnerCategoryNo);
            }
        } else {
            queryWrapper.eq(ShopGoodsCategory::getLevel, 1);
        }
        queryWrapper.orderByDesc(ShopGoodsCategory::getSort);
        return BaseResponse.success(list(queryWrapper));
    }

    public BaseResponse addGoodsCategory(ShopGoodsCategoryAddParams params) {
        if (ToolUtil.isOneEmpty(params.getCategoryName(), params.getLevel())) {
            return BaseResponse.error("当前上级分类参数有误");
        }
        if (params.getLevel().equals(1)) {
            params.setPartnerCategoryNo("0");
        } else if (params.getLevel().equals(2)) {
            if (ToolUtil.isEmpty(params.getPartnerCategoryNo())) {
                return BaseResponse.error("当前上级分类有误");
            }
        } else {
            return BaseResponse.error("当前分类等级有误");
        }
        ShopGoodsCategory shopGoodsCategory = EntityConvertUtils.convertAToB(params, ShopGoodsCategory.class);
        shopGoodsCategory.setCategoryNo(RedisUtil.getServiceKeyHaveDateByType(ServiceKeyTypeEnum.GOODS_CATEGORY.getValue()));
        shopGoodsCategory.setSort(ToolUtil.isNotEmpty(params.getSort()) ? params.getSort() : 0);
        shopGoodsCategory.setIsShow(true);
        shopGoodsCategory.setIsDeleted(false);
        Date time = new Date();
        shopGoodsCategory.setCreateTime(time);
        shopGoodsCategory.setUpdateTime(time);
        saveOrUpdate(shopGoodsCategory);
        return BaseResponse.success("成功");
    }

    @Transactional(rollbackFor = {Exception.class, BizException.class, NoMsgException.class})
    public BaseResponse deleteGoodsCategory(Long id) {
        ShopGoodsCategory shopGoodsCategory = getById(id);
        //是否是1级
        Integer level = shopGoodsCategory.getLevel();
        String categoryNoOne = shopGoodsCategory.getCategoryNo();
        try {
            //查询类目下是否有未删除商品
            if (level.equals(1)) {
                //（查询是否有挂靠商品）
                List<ShopGoods> shopGoodsList = shopGoodsService.queryByCategoryNo(categoryNoOne);
                if (ToolUtil.isNotEmpty(shopGoodsList)) {
                    ShopGoods shopGoods = shopGoodsList.get(0);
                    throw new NoMsgException("当前类目下,至少还存在商品【" + shopGoods.getGoodsName() + "】没有删除");
                }
                shopGoodsCategory.setUpdateTime(new Date());
                shopGoodsCategory.setIsDeleted(true);
                this.saveOrUpdate(shopGoodsCategory);
                return BaseResponse.success("删除商品类目成功");
//                //查询2级编号
//                List<ShopGoodsCategory> level2 = queryByPartnerNo(categoryNoOne);
//                if (ToolUtil.isEmpty(level2)) {
//                    shopGoodsCategory.setUpdateTime(new Date());
//                    shopGoodsCategory.setIsDeleted(true);
//                } else {
//                    //2级分类的处理
//                    for (ShopGoodsCategory goodsCategory : level2) {
//                        String categoryNoTwo = goodsCategory.getCategoryNo();
//                        List<ShopGoods> shopGoodsList = shopGoodsService.queryByCategoryNo(categoryNoTwo);
//                        if (ToolUtil.isNotEmpty(shopGoodsList)) {
//                            ShopGoods shopGoods = shopGoodsList.get(0);
//                            throw new NoMsgException("当前类目下,至少还存在商品【" + shopGoods.getGoodsName() + "】没有删除");
//                        }
//                        goodsCategory.setUpdateTime(new Date());
//                        goodsCategory.setIsDeleted(true);
//                        this.saveOrUpdate(goodsCategory);
//                    }
//                    shopGoodsCategory.setUpdateTime(new Date());
//                    shopGoodsCategory.setIsDeleted(true);
//                }
//                this.saveOrUpdate(shopGoodsCategory);
//                return BaseResponse.success("删除商品类目成功");
            } else {
                //（查询是否有挂靠商品）
                List<ShopGoods> shopGoodsList = shopGoodsService.queryByCategoryNo(categoryNoOne);
                if (ToolUtil.isNotEmpty(shopGoodsList)) {
                    ShopGoods shopGoods = shopGoodsList.get(0);
                    throw new NoMsgException("当前类目下,至少还存在商品【" + shopGoods.getGoodsName() + "】没有删除");
                }
                shopGoodsCategory.setUpdateTime(new Date());
                shopGoodsCategory.setIsDeleted(true);
                this.saveOrUpdate(shopGoodsCategory);
                return BaseResponse.success("删除商品类目成功");
            }
        } catch (BizException e) {
            return BaseResponse.error(e.getErrorMessage());
        }
    }

    @Transactional(rollbackFor = {Exception.class, BizException.class, NoMsgException.class})
    public BaseResponse reviewGoodsCategory(Long id, Boolean letDisable) {
        ShopGoodsCategory shopGoodsCategory = getById(id);
        //是否是1级
        Integer level = shopGoodsCategory.getLevel();
        String categoryNoOne = shopGoodsCategory.getCategoryNo();
        try {
            //查询类目下是否有未删除商品
            if (level.equals(1)) {
                //查询2级编号
                List<ShopGoodsCategory> level2 = queryByPartnerNo(categoryNoOne);
                if (ToolUtil.isEmpty(level2)) {
                    if (letDisable) {
                        shopGoodsCategory.setIsShow(false);
                    } else {
                        shopGoodsCategory.setIsShow(true);
                    }
                } else {
                    //2级分类的处理
                    for (ShopGoodsCategory goodsCategory : level2) {
                        String categoryNoTwo = goodsCategory.getCategoryNo();
                        //禁用（查询是否有挂靠商品）
                        if (letDisable) {
                            List<ShopGoods> shopGoodsList = shopGoodsService.queryByCategoryNo(categoryNoTwo);
                            if (ToolUtil.isNotEmpty(shopGoodsList)) {
                                ShopGoods shopGoods = shopGoodsList.get(0);
                                throw new NoMsgException("当前类目下,至少还存在商品【" + shopGoods.getGoodsName() + "】没有删除");
                            }
                            goodsCategory.setIsShow(false);
                        } else {
                            goodsCategory.setIsShow(true);
                        }
                        this.saveOrUpdate(goodsCategory);
                    }
                    //1级分类的处理
                    if (letDisable) {
                        shopGoodsCategory.setIsShow(false);
                    } else {
                        shopGoodsCategory.setIsShow(true);
                    }
                }
                this.saveOrUpdate(shopGoodsCategory);
                return BaseResponse.success("禁启用商品类目成功");
            } else {
                //禁用（查询是否有挂靠商品）
                if (letDisable) {
                    List<ShopGoods> shopGoodsList = shopGoodsService.queryByCategoryNo(categoryNoOne);
                    if (ToolUtil.isNotEmpty(shopGoodsList)) {
                        ShopGoods shopGoods = shopGoodsList.get(0);
                        throw new NoMsgException("当前类目下,至少还存在商品【" + shopGoods.getGoodsName() + "】没有删除");
                    }
                    shopGoodsCategory.setIsShow(false);
                } else {
                    shopGoodsCategory.setIsShow(true);
                }
                this.saveOrUpdate(shopGoodsCategory);
                return BaseResponse.success("禁启用商品类目成功");
            }
        } catch (BizException e) {
            return BaseResponse.error(e.getErrorMessage());
        }
    }

    private List<ShopGoodsCategory> queryByPartnerNo(String categoryNo) {
        LambdaQueryWrapper<ShopGoodsCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopGoodsCategory::getPartnerCategoryNo, categoryNo);
        return list(queryWrapper);
    }

    public List<ShopGoodsCategory> queryLevelTwo() {
        LambdaQueryWrapper<ShopGoodsCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopGoodsCategory::getLevel, 2);
        queryWrapper.eq(ShopGoodsCategory::getIsDeleted, false);
        return list(queryWrapper);
    }

    public List<ShopGoodsCategory> queryLevelOne() {
        LambdaQueryWrapper<ShopGoodsCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopGoodsCategory::getLevel, 1);
        queryWrapper.eq(ShopGoodsCategory::getIsDeleted, false);
        return list(queryWrapper);
    }

    public ShopGoodsCategory queryByCategoryNo(String categoryNo) {
        if (ToolUtil.isEmpty(categoryNo)) {
            return null;
        }
        LambdaQueryWrapper<ShopGoodsCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopGoodsCategory::getCategoryNo, categoryNo);
        return getOne(queryWrapper);
    }

    public BaseResponse editGoodsCategory(ShopGoodsCategoryEditParams params) {
        LambdaUpdateWrapper<ShopGoodsCategory> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(ShopGoodsCategory::getUpdateTime, new Date());
        if (ToolUtil.isNotEmpty(params.getCategoryName())) {
            updateWrapper.set(ShopGoodsCategory::getCategoryName, params.getCategoryName());
        }
        if (ToolUtil.isNotEmpty(params.getCategoryImg())) {
            updateWrapper.set(ShopGoodsCategory::getCategoryImg, params.getCategoryImg());
        }
        if (ToolUtil.isNotEmpty(params.getSort())) {
            updateWrapper.set(ShopGoodsCategory::getSort, params.getSort());
        }
        updateWrapper.eq(ShopGoodsCategory::getId, params.getId());
        this.update(updateWrapper);
        return BaseResponse.success("修改成功");
    }

    public BaseResponse<List<ShopGoodsCategoryTreeResult>> goodsCategoryList(Boolean isGop) {
        LambdaQueryWrapper<ShopGoodsCategory> queryWrapper = new LambdaQueryWrapper<>();
        if (!isGop) {
            queryWrapper.eq(ShopGoodsCategory::getIsShow, true);
        }
        queryWrapper.eq(ShopGoodsCategory::getIsDeleted, false);
        queryWrapper.orderByDesc(ShopGoodsCategory::getSort);
        List<ShopGoodsCategory> shopGoodsCategoryListAll = list(queryWrapper);
        List<ShopGoodsCategory> shopGoodsCategoryListFirst = shopGoodsCategoryListAll.stream().filter(x -> x.getLevel().equals(1)).collect(Collectors.toList());
        List<ShopGoodsCategoryTreeResult> resultList = EntityConvertUtils.convertAListToBList(shopGoodsCategoryListFirst, ShopGoodsCategoryTreeResult.class);
        List<ShopGoods> shopGoodsListAll = shopGoodsService.listNoDeletedGoodsList();
        for (ShopGoodsCategoryTreeResult treeResult : resultList) {
            String partnerCategoryNo = treeResult.getCategoryNo();
            List<ShopGoodsCategory> shopGoodsCategoryListTwo = shopGoodsCategoryListAll.stream().filter(
                    x -> x.getLevel().equals(2) && x.getPartnerCategoryNo().equals(partnerCategoryNo)).collect(Collectors.toList());
            List<ShopGoodsCategoryTreeResult> sonResults = EntityConvertUtils.convertAListToBList(shopGoodsCategoryListTwo, ShopGoodsCategoryTreeResult.class);
            //绑定至一级的商品数量
            List<ShopGoods> shopGoodsListA = shopGoodsListAll.stream().filter(x -> x.getGoodsCategoryNo().equals(partnerCategoryNo)).collect(Collectors.toList());
            treeResult.setGoodsCount(ToolUtil.isNotEmpty(shopGoodsListA) ? shopGoodsListA.size() : 0);
            for (ShopGoodsCategoryTreeResult sonResult : sonResults) {
                String sonCategoryNo = sonResult.getCategoryNo();
                List<ShopGoods> shopGoodsList = shopGoodsListAll.stream().filter(x -> x.getGoodsCategoryNo().equals(sonCategoryNo)).collect(Collectors.toList());
                sonResult.setGoodsCount(ToolUtil.isNotEmpty(shopGoodsList) ? shopGoodsList.size() : 0);
            }
            treeResult.setSonResults(sonResults);
        }
        return BaseResponse.success(resultList);
    }

    public BaseResponse<List<GoodsCategoryParams>> goodsCategoryFirstList() {
        return BaseResponse.success(EntityConvertUtils.convertAListToBList(
                queryGoodsCategory(1, null, false).getData(), GoodsCategoryParams.class));
    }

}
